package driver

import (
	"github.com/neo4j/neo4j-go-driver/v4/neo4j"
	"go.uber.org/zap"
)

// Neo4j 驱动
type Neo4j struct {
	client neo4j.Driver
}

// new client
func NewDriver(log *zap.Logger, url, username, password, realm string) (*Neo4j, error) {
	driver, err := neo4j.NewDriver(url, neo4j.BasicAuth(username, password, realm))
	if err != nil {
		log.Error("init neo4j client err")
		return nil, err
	}
	return &Neo4j{
		client: driver,
	}, nil
}

type Neo4jInterface interface {
	Do(in func(tx neo4j.Transaction) (interface{}, error)) (interface{}, error)
	Close()
}

func (n *Neo4j) Do(in func(tx neo4j.Transaction) (interface{}, error)) (interface{}, error) {
	session := n.client.NewSession(neo4j.SessionConfig{})
	defer session.Close()
	result, err := session.WriteTransaction(in)
	if err != nil {
		return nil, nil
	}
	return result, nil
}

func (n *Neo4j) Close() {
	n.client.Close()
}
